package mvpfoot.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.HashMap;

import mvpfoot.entity.GoodsBean;

/**
 * Created by Chen qin lang on 2017/1/9.
 */
public class MySqlite extends OrmLiteSqliteOpenHelper {
    private static final String DATABASENAME="database.db";
    private static final int DATABASEVERSION=1;
    private static MySqlite mySqlite;
    private MySqlite(Context context) {
        super(context, DATABASENAME, null, DATABASEVERSION);
    }
    public static MySqlite getMySqlite(Context context){
        if (mySqlite==null){
            synchronized (DATABASENAME){
                if (mySqlite==null){
                    mySqlite=new MySqlite(context);
                }
            }
        }
        return mySqlite;
    }
    //存储表结构到缓存中
    public HashMap<String,Dao> daos=new HashMap<>();
    public synchronized Dao getDao(Class aClass){
        Dao dao=null;
        String dbName=aClass.getSimpleName();
        //记录下访问的数据库 避免重复创建
        if (daos.containsKey(dbName)){
            dao=daos.get(dbName);
        }else{
            try {
                dao=super.getDao(aClass);
                daos.put(dbName,dao);
            } catch (SQLException e) {
                e.printStackTrace();
                new RuntimeException("表无法创建,请输入正确的表");
            }

        }
        return dao;
    }
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, GoodsBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            TableUtils.dropTable(connectionSource,GoodsBean.class,true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void close(){
        for (String s :daos.keySet()){

        }
    }
}
